package com.insyte.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 11/03/2015.
 */
public class MultipleScreen {
    private Context context;
    private float with_dp, height_dp;
    private float with_px, height_px;
    private DisplayMetrics metrics;
    private static final String TAG = "MultipleScreen";
    public static final float DEFAULT_ANDROID_SCALE = 0.5f;
    private static final int TWO_MINUTES = 1000 * 60 * 2;

    public static int nH;
    public static int nW;
    private static float nImageW = 768;
    private static float nImageH = 1280;
    private static float fScale = 1;

    public MultipleScreen() {
    }

    public MultipleScreen(Context context) {
        this.context = context;
        getDpiOfScreen();
    }

    public void getDpiOfScreen() {
        metrics = context.getResources().getDisplayMetrics();
        with_px = metrics.widthPixels;
        height_px = metrics.heightPixels;
        // dp = px / ( metrics.densityDpi / 160f )
        with_dp = with_px / (metrics.densityDpi / 160f);
        height_dp = height_px / (metrics.densityDpi / 160f);
    }


    public int convertPxToDp(float px) {
        return (int) (px / (metrics.densityDpi / 160f));
    }

    public void getWithHeight(View v) {

    }

    public void setSizeTextView(TextView tv, float division, float multiplication) {
        if (division > 1 && multiplication == 0) {
            division = 1;
            multiplication = 1;
        }
        int tv_height_px = tv.getLineHeight();
        int tv_height_dp = (int) (convertPxToDp(tv_height_px) / division * multiplication);
        tv.setTextSize(tv_height_dp);
    }

    public void setSizeView(View view) {

    }

    public float getWith_dp() {
        return with_dp;
    }

    public float getHeight_dp() {
        return height_dp;
    }

    public float getHeight_px() {
        return height_px;
    }

    public float getWith_px() {
        return with_px;
    }

    public void setDpView(View v) {
        v.getLayoutParams().width = 50;
        v.getLayoutParams().height = 50;
    }

    //thangpv
    public static void showToast(Context ctx, String msg) {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }

    public static void logMessage(String msg) {
        Log.d("thangpv", msg);
    }

    public static float getScale(Context ctx) {
        //Context ctx = ac.getApplicationContext();
//		Display display = ac.getWindowManager()
//				.getDefaultDisplay();
        DisplayMetrics metrics = ctx.getResources().getDisplayMetrics();
        //Point rect = getSize(display, ac);
        nW = metrics.widthPixels;
        nH = metrics.heightPixels;
        Log.d("thangpv", "rect.y = " + nW);
        Log.d("thangpv", "rect.x = " + nH);
        if ((float) (nH / nImageH) <= (float) (nW / nImageW)) {
            fScale = nH / nImageH;
        } else {
            fScale = nW / nImageW;
        }
        return fScale;
    }

    public static Point getRealSize(Display display) {
        Point outPoint = new Point();
        Method mGetRawH;
        try {
            mGetRawH = Display.class.getMethod("getRawHeight");
            Method mGetRawW = Display.class.getMethod("getRawWidth");
            outPoint.x = (Integer) mGetRawW.invoke(display);
            outPoint.y = (Integer) mGetRawH.invoke(display);
            return outPoint;
        } catch (Throwable e) {
            return null;
        }
    }

    public static Point getSize(Display display, Activity ac) {
        if (Build.VERSION.SDK_INT >= 17) {
            Point outPoint = new Point();
            DisplayMetrics metrics = ac.getResources().getDisplayMetrics();
            outPoint.x = metrics.widthPixels;
            outPoint.y = metrics.heightPixels;
            return outPoint;
        }
        if (Build.VERSION.SDK_INT >= 14) {
            Point outPoint = getRealSize(display);
            if (outPoint != null)
                return outPoint;
        }
        Point outPoint = new Point();
        if (Build.VERSION.SDK_INT >= 13) {
            display.getSize(outPoint);
        } else {
            outPoint.x = display.getWidth();
            outPoint.y = display.getHeight();
        }
        return outPoint;
    }

    public static float getScreenWidth(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return metrics.widthPixels;
    }

    public static float convertDpToPixels(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return px;
    }

    public static boolean isNetworkAvailable(Context ctx) {
        ConnectivityManager connectivity = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static int calculateInSize(BitmapFactory.Options options,
                                      int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        float fScale = reqHeight / height;
        float reqWidth = height * fScale;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    public static Bitmap readBitmapLarg(Context ctx, Uri uriImage, int reqHeight) {

        Bitmap bitmap = null;
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        try {
            bitmap = BitmapFactory.decodeStream(ctx.getContentResolver()
                    .openInputStream(uriImage), null, options);
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Calculate inSampleSize
        options.inSampleSize = calculateInSize(options, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        try {
            bitmap = BitmapFactory.decodeStream(ctx.getContentResolver()
                    .openInputStream(uriImage), null, options);

        } catch (Exception e) {
            bitmap = null;
        }
        return bitmap;
    }

    public static Bitmap readBitmapLarg(Context ctx, String urlImage,
                                        int reqHeight) {
        Bitmap bitmap = null;
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        try {
            bitmap = BitmapFactory.decodeFile(urlImage, options);
        } catch (Exception e) {
            // TODO: handle exception
        }
        // Calculate inSampleSize
        options.inSampleSize = calculateInSize(options, reqHeight);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        try {
            bitmap = BitmapFactory.decodeFile(urlImage, options);
        } catch (Exception e) {
            bitmap = null;
        }
        return bitmap;
    }

    public static Bitmap scaleBitmap(Bitmap bmp, int reqWidth, int reqHeight) {

        float sampleSize = calculateInSampleSize(bmp.getWidth(),
                bmp.getHeight(), reqWidth, reqHeight);
        Log.d(TAG, "inSameple Size " + sampleSize);
        try {
            if (sampleSize > 1) {
                return scaleBitmap(bmp, 1f / sampleSize);
            } else {
                return bmp;
            }

        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        return bmp;
    }

    public static Bitmap scaleBitmap(Bitmap bmp, float scale) {
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        return Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(),
                matrix, true);

    }

    public static float calculateInSampleSize(int width, int height,
                                              int reqWidth, int reqHeight) {
        // Raw height and width of image

        float inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final float heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final float widthRatio = Math.round((float) width
                    / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    public static boolean checkAirPlaneMode(Context context) {
        return Settings.System.getInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    }

    public static AlertDialog showDialog(Context context, String title,
                                         String mesage) {
        try {
            AlertDialog dialog = new AlertDialog.Builder(context).create();
            dialog.setCancelable(false);
            if (title != null) {
                dialog.setTitle(title);
            }
            dialog.setMessage(mesage);
            dialog.setButton("Close", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialog.show();
            return dialog;
        } catch (Exception e) {
            Log.d(TAG, "show dialog cancel");
            return null;
        }
    }

}
